package com.zxshhy.conmuser;

import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.client.Channel;
import com.zxshhy.config.RabbitMqConfig;
import com.zxshhy.service.BalanceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

@Slf4j
@Component
public class BalanceConsumer {

    @Resource
    private BalanceService balanceService;

    /**
     * 库存扣减
     * @param orderMessage
     * @param channel
     * @param message
     * @throws IOException
     */
//    @RabbitListener(queues = RabbitMqConfig.ZXSHHY_BALANCE_QUEUE)
    @RabbitListener(
            bindings = {
                    @QueueBinding(value = @Queue(value = RabbitMqConfig.ZXSHHY_BALANCE_QUEUE, durable = "true"),
                            exchange = @Exchange(value = RabbitMqConfig.ZXSHHY_DIRECT_EXCHANGE),
                            key = RabbitMqConfig.ZXSHHY_BALANCE_ROUTINGKEY)
            })
    @RabbitHandler
    public void receiveBalanceDebitQueueMsg(String orderMessage, Channel channel, Message message) throws IOException {
        log.info("接收到余额扣减队列消息：{}", orderMessage);
        try {
            JSONObject jsonObject = JSONObject.parseObject(orderMessage);
            String userId = jsonObject.getString("userId");
            Integer money = jsonObject.getInteger("money");
            // 用户账户余额扣款
            balanceService.debit(userId, money);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            log.info("用户【{}】账户余额扣款成功：{}",userId,money);
        } catch (IOException e) {
            log.error("库存扣减异常：", e);
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
        }
    }
}
